﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace Fly.Common.Utils
{
    /// <summary>
    /// 工具类扩展
    /// </summary>
    public static class MyUtility
    {
        #region 分钟格式化
        /// <summary>
        /// 在当前时间上增加指定的分钟数并转换为可读字符串
        /// </summary>
        /// <param name="times"></param>
        /// <returns></returns>
        public static string AddMinutes(int times)
        {
            return DateTime.Now.AddMinutes(times).ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 在当前时间上增加指定的分钟数并转换为可读字符串
        /// </summary>
        /// <param name="times">分钟数</param>
        /// <param name="format">格式化的日期格式</param>
        /// <returns></returns>
        public static string AddMinutes(int times, string format)
        {

            return DateTime.Now.AddMinutes(times).ToString(format);
        } 
        #endregion

        #region 判断指定的字符串是否是十六进制表示的颜色值
        /// <summary>
        /// 判断指定的字符串是否是十六进制表示的颜色值
        /// </summary>
        /// <param name="color">需要判断的字符串</param>
        /// <returns></returns>
        public static bool IsColorValue(string color)
        {
            if (string.IsNullOrWhiteSpace(color))
            {
                return false;
            }
            color = color.Trim().Trim(new[] { '#' });
            if (color.Length != 3 && color.Length != 6)
            {
                return false;
            }
            if (!Regex.IsMatch(color, "[^0-9a-f]", RegexOptions.IgnoreCase))
            {
                return true;
            }
            return false;
        } 
        #endregion

        #region 将指定的时间转换为 Unix 时间戳
        /// <summary>
        /// 将指定的时间转换为 Unix 时间戳
        /// </summary>
        /// <param name="date">一个指定的日期</param>
        /// <returns></returns>
        public static double ConvertToUnixTimestamp(DateTime date)
        {
            DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Math.Floor((date - dateTime).TotalSeconds);
        } 
        #endregion

        #region 获取字符串表示的 Guid
        /// <summary>
        /// 获取字符串表示的 Guid
        /// </summary>
        /// <returns></returns>
        public static string NewGuid()
        {
            return string.Concat("{", Guid.NewGuid().ToString(), "}");
        } 
        #endregion

        #region 从指定控件中查找指定 ID 的子控件
        /// <summary>
        /// 从指定控件中查找指定 ID 的子控件
        /// </summary>
        /// <param name="id">子控件的ID</param>
        /// <param name="container">父控件</param>
        /// <returns></returns>
        public static Control FindControl(string id, Control container)
        {
            Control control;
            foreach (Control control1 in container.Controls)
            {
                if (control1.ID != id)
                {
                    continue;
                }
                control = control1;
                return control;
            }
            IEnumerator enumerator = container.Controls.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    Control control2 = FindControl(id, (Control)enumerator.Current);
                    if (control2 == null)
                    {
                        continue;
                    }
                    control = control2;
                    return control;
                }
                return null;
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        } 
        #endregion

        #region 文件大小单位转换

        /// <summary>
        /// 将字节大小转换为可读的合适的大小
        /// </summary>
        /// <param name="bytes">字节长度</param>
        /// <returns></returns>
        public static string FormatBytesString(long bytes)
        {
            const int unit = 1024;
            if (bytes < unit) return bytes + " B";
            int exp = (int)(Math.Log(bytes) / Math.Log(unit));
            return String.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), "KMGTPE"[exp - 1]);
        }

        #endregion

        #region 获取当前日期可读的字符串
        /// <summary>
        /// 获取当前日期可读的字符串
        /// </summary>
        /// <param name="format">格式化的日期格式</param>
        /// <returns></returns>
        public static string GetDate(string format = "yyyy-MM-dd")
        {
            return DateTime.Now.ToString(format);
        }
        /// <summary>
        /// 获取当前日期可读的字符串
        /// </summary>
        /// <returns></returns>
        public static string GetDate(DateTime date, string format = "yyyy-MM-dd")
        {
            return date.ToString(format);
        } 
        #endregion

        #region 格式化可空的日期
        /// <summary>
        /// 格式化可空的日期
        /// </summary>
        /// <param name="dateTime">可空的日期</param>
        /// <param name="format">格式化的日期格式</param>
        /// <returns></returns>
        public static string FormatDateTime(DateTime? dateTime, string format = "yyyy-MM-dd")
        {
            if (dateTime == null)
            {
                return string.Empty;
            }
            return ((DateTime)dateTime).ToString(format);
        }
        /// <summary>
        /// 格式化字符串表示的日期
        /// </summary>
        /// <param name="date">需要格式化的字符串表示的日期</param>
        /// <param name="format">格式化的日期格式</param>
        /// <returns></returns>
        public static string FormatDateTime(string date, string format = "yyyy-MM-dd")
        {
            if (string.IsNullOrWhiteSpace(date))
            {
                return date;
            }
            DateTime time;
            if (DateTime.TryParse(date, out time))
            {
                return time.ToString(format);
            }
            return date;
        } 
        #endregion

        #region 格式化十进制表示的可空类型
        /// <summary>
        /// 格式化十进制表示的可空类型
        /// </summary>
        /// <param name="money">可空的十进制</param>
        /// <param name="format">格式化的十进制格式</param>
        /// <returns></returns>
        public static string FormatDecimal(decimal? money, string format = "0.00")
        {
            if (money == null)
            {
                return string.Empty;
            }
            return ((decimal)money).ToString(format);
        } 
        #endregion

        #region 获取电子邮件的域名
        /// <summary>
        /// 获取电子邮件的域名
        /// </summary>
        /// <param name="strEmail">字符串表示的邮件地址</param>
        /// <returns></returns>
        public static string GetEmailHostName(string strEmail)
        {
            if (string.IsNullOrWhiteSpace(strEmail))
            {
                return string.Empty;
            }
            if (strEmail.IndexOf("@", StringComparison.OrdinalIgnoreCase) < 0)
            {
                return string.Empty;
            }
            return strEmail.Substring(strEmail.LastIndexOf("@", StringComparison.OrdinalIgnoreCase)).ToLower();
        } 
        #endregion

        #region 获取文件后缀名
        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static string GetFileExtName(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName) || fileName.IndexOf('.') <= 0)
            {
                return "";
            }
            fileName = fileName.ToLower().Trim();
            return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
        } 
        #endregion

        #region 获取指定 URL 地址的文件名
        /// <summary>
        /// 获取指定 URL 地址的文件名
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetFileName(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return string.Empty;
            }
            string[] strArrays = url.Split(new[] { '/' });
            string str = strArrays[strArrays.Length - 1];
            char[] chrArray = { '?' };
            return str.Split(chrArray)[0];
        } 
        #endregion

        #region 获取空白
        /// <summary>
        /// 获取指定个数的 Html 空格符
        /// </summary>
        /// <param name="spacesCount">字符个数</param>
        /// <returns></returns>
        public static string GetHtmlSpaces(int spacesCount)
        {
            StringBuilder stringBuilder = new StringBuilder(spacesCount + 1);
            for (int i = 0; i < spacesCount; i++)
            {
                stringBuilder.Append("&nbsp;");
            }
            return stringBuilder.ToString();
        }
        /// <summary>
        /// 获取指定个数的空白
        /// </summary>
        /// <param name="spacesCount">空白个数</param>
        /// <returns></returns>
        public static string GetSpaces(int spacesCount)
        {
            StringBuilder stringBuilder = new StringBuilder(spacesCount + 1);
            for (int i = 0; i < spacesCount; i++)
            {
                stringBuilder.Append(" ");
            }
            return stringBuilder.ToString();
        }
        #endregion

        #region 移除 Html 标签
        /// <summary>
        /// 移除 Html 标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            return Regex.Replace(content, "<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 移除不安全的 Html 标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, "(\\<|\\s+)o([a-z]+\\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, "(script|frame|form|meta|behavior|style)([\\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        } 
        #endregion

    }
}
